package cool.tianyou.blue.bird;

import android.content.Context;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;

import cool.tianyou.blue.bird.util.HttpUtil;

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    Context mContext;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("e", exceptionToString(e));
        new Thread(() -> HttpUtil.post(mContext, map, "/log", apiResult -> {
        }));

    }

    public String exceptionToString(Throwable e) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        e.printStackTrace(writer);
        Throwable cause = e.getCause();
        while (cause != null) {
            cause.printStackTrace(writer);
            cause = e.getCause();
        }
        writer.close();
        return stringWriter.toString();
    }


    public void register(Context context) {
        mContext = context;
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
}
